Python : 3.6.3
布尔表达式
条件测试:每条 if 语句的核心都是一个值为 true 或 false 的表达式
表达式也称为布尔表达式
检查是否相等
大多数条件测试都是将一个变量的当前值同特定值通过相等运算符进行比较。1
car == 'bmw'
检查是否相等时不考虑大小写
在 Python 中检查是否相等时默认区分大小写。
不过某些特殊场景下可以使用 lower() 方法对测试变量进行临时处理后再比较:1
2car = 'Audi'
car.lower() == 'audi'
检查是否不相等
要判断两个值是否不等,可使用 “!=”:1
2
3
4requested_topping = 'mushrooms'
if requested_topping != 'anchovies':
print("Hold the anchovies!")
检查多个条件
####### 使用 and 检查多个条件
and 表示并且,需要两个条件都为 true,表达式才为 true:1
2
3age_0 = 22
age_1 = 18
print(age_0 >= 21 and age_1 >= 21)
为了提高可读性,可以使用括号:1
2
3age_0 = 22
age_1 = 18
print((age_0 >= 21) and (age_1 >= 21))
####### 使用 or 检查多个条件
or 表示或,需要两个条件都为 false,表达式才为 false:1
2
3age_0 = 18
age_1 = 18
print(age_0 >= 21 or age_1 >= 21)
为了提高可读性,可以使用括号:1
2
3age_0 = 18
age_1 = 18
print((age_0 >= 21) or (age_1 >= 21)
检查特定值是否包含在列表中
Python 可以使用关键字 in 判断特定的值是否已包含在列表中:1
2requested_toppings = ['mushrooms','onions','pineapple']
print('mushrooms' in requested_toppings)
检查特定值是否不包含在列表中
Python 可以使用关键字 not in 判断特定的值是否未包含在列表中:1
2requested_toppings = [onions','pineapple']
print('mushrooms' not in requested_toppings)
if 语句
简单的 if 语句
最简单的 if 语句只有一个布尔表达式和一个操作:1
2
3
4age = 19
if age >= 18:
print("You are old enough to vote!")
print("Have you registered to vote yet?")
if 语句的缩进和 for 语句的规则一致。
if-else 语句
if-else 语句中若布尔表达式结果为 true,则执行 if 中的语句,反之执行 else 中的语句:1
2
3
4
5
6
7age = 17
if age >= 18:
print("You are old enough to vote!")
print(" Have you registered to vote yet?")
else:
print("Sorry,you are too young to vote.")
print("Please register to vote as soon as you turn 18!")
if-elif-else 语句
if-elif-else 依次检查每个条件测试,直到遇到通过了的条件测试。
测试通过后,Python 将执行紧跟在它后面的代码,并跳过余下的测试。
1 | age = 12 |
测试多个条件
在可能有多个条件为 true,且需要在每个条件为 true 时都执行:1
2
3
4
5
6
7
8requested_toppings = ['mushrooms','extra cheese']
if 'mushrooms' in requested_toppings:
print("Adding mushrooms")
if 'pepperoni' in requested_toppings:
print("Adding pepperoni")
if 'extra cheese' in requested_toppings:
print("Adding extra cheese")
输出:1
2Adding mushrooms
Adding extra cheese
使用 if 语句处理列表
检查特殊元素
1 | requested_toppings = ['mushrooms','green peppers','extra cheese'] |
输出:1
2
3
4Adding mushrooms
Sorry, we are out of green peppers right now
Adding extra cheese
Finished making your pizza!
确定列表不是空的
1 | requested_toppings = [] |
输出:1
Are you sure you want a plain pizza?
使用多个列表
1 | available_toppings = ['mushrooms','olives','green peppers','pepperoni','pineapple','extra cheese'] |
输出:
1 | Adding mushrooms |